package com.docted.design.pattern.proxy.dynamic.customer;

import java.io.*;

/**
 * @author DoCted
 * @since v1.0 2018/3/11
 */
public class DocClassLoader extends ClassLoader {


    private File classPath;

    public DocClassLoader() {
        String classPath = DocClassLoader.class.getResource("").getPath();
        this.classPath = new File(classPath);
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        String className = DocClassLoader.class.getPackage().getName() + "." + name;

        if (classPath != null) {
            File classFile = new File(classPath, name.replaceAll("\\.", "/") + ".class");
            if (classFile.exists()) {
                FileInputStream fileInputStream = null;

                ByteArrayOutputStream byteArrayOutputStream = null;

                try {
                    fileInputStream = new FileInputStream(classFile);
                    byteArrayOutputStream = new ByteArrayOutputStream();

                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = fileInputStream.read(buffer)) != -1) {
                        byteArrayOutputStream.write(buffer, 0, len);
                    }

                    return defineClass(className, byteArrayOutputStream.toByteArray(), 0, byteArrayOutputStream.size());


                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
